import axios from 'axios'
import { Message } from "element-ui";
import Qs from "qs"
import Cookies from 'js-cookie'
// 创建一个axios实例
axios.defaults.baseURL = process.env.VUE_APP_BASEURL;
axios.defaults.timeout = 20000;
axios.defaults.headers["Content-Type"] = "application/json";
/**
 * 请求拦截器
 */
axios.interceptors.request.use(
    (config) => {
      var configUrl = config.url
      var flag = configUrl.includes("/api");
      var token = Cookies.get("tooken"); 
      if (!flag&&token) {
        config.headers["Authorization"] = token
      }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)
/**
 * 响应拦截器
 */
axios.interceptors.response.use(
    (res) => {
      if (res.status==200&&res.data.status==0) {
        return Promise.resolve(res)
      }else{
        return Promise.reject(res); 
      }
    }
  )
/** 
 * get方法，对应get请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
export function get(url,data, params){    
  return new Promise((resolve, reject) =>{    
    axios({
      method: 'get',
      url: url,
      data : data,
      params:params
    }).then(res => {    
          resolve(res.data);        
      }).catch(err => {            
          reject(err.data);
          Message.error(res.data.message)       
      })    
  });
}
/** 
* post方法，对应post请求 
* @param {String} url [请求的url地址] 
* @param {Object} params [请求时携带的参数] 
*/
export function post(url, params) {    
  return new Promise((resolve, reject) => {     
      axios.post(url, Qs.stringify(params))        
      .then(res => {            
          resolve(res.data);        
      })              
      .catch(err => {        
          reject(err.data)        
      })    
  });
}

export function postForm(url,data){
  return new Promise((resolve, reject) => {         
    axios({
      method: 'post',
        url: url,
        headers: { 
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data : data
    }).then(res => {   
      resolve(res.data);  
      if (res.data.status==0) {
        Message.success(res.data.message)
      }else{
        Message.error(res.data.message)
      }  
    })        
    .catch(err => {            
        reject(err.data);
        Message.error(err.data.message)
    })
});
}